<?php
namespace Auth\Api;

use PhalApi\Api;
use PhalApi\Exception\BadRequestException;
use JiaweiXS\WeApp\WeApp;
use App\Common\Base64 as Base64;
use App\Domain\Appfc114\User as DomainUser;
use Crm\Domain\WxUser as WxUser;
use Crm\Domain\SysUser as SysUser;
use Crm\Domain\Score as Score;
use Crm\Domain\Company as Company;

/**
 * 默认接口服务类
 *
 * @author: dogstar <chanzonghuang@gmail.com> 2014-10-04
 */

class Token extends Api {

    public $key;            //key值 数据库保存md5值格式为:md5(密码+key) 防止破译md5

    public $user_type_option;

    public function __construct()
    {
        //允许所有域名发起的跨域请求
        header("Access-Control-Allow-Origin: *");
        //$this->di = \PhalApi\DI();
        $this->key = 'fc114'; //设定过后不能修改 否则验证会通不过
        $this->user_type_option = \PhalApi\DI()->config->get('basecode.wx_user_type_option');
    }

	public function getRules() {
        return array(
            // 获取HTTP请求方法，判断是POST还是GET

            'accessToken' => array(
                'openid' => array('name' => 'openid','require'=>true,'desc'=>'openid'),
                'nickname' => array('name' => 'nickname','require'=>true,'desc'=>'微信昵称'),
                'sex' => array('name' => 'sex','require'=>false,'desc'=>'性别'),
                'headimgurl' => array('name' => 'headimgurl','require'=>false,'desc'=>'头像'),
                'mall_id' => array('name' => 'mall_id','type'=>'int','default'=>0, 'require'=>false,'desc'=>'商城ID')
            ),
            'refreshToken' => array(),

            'getOpenId'=>[
                'code'=>['name' => 'code', 'type'=>'string', 'require' => true, 'desc' => '微信code'],
                'appid'=>['name' => 'appid', 'type'=>'string', 'require' => false, 'desc' => '小程序Appid']
            ],

            'login'=>array(
                'mobile' => array('name' => 'mobile','require'=>true,'desc'=>'用户手机'),
                'password' => array('name' => 'password','require'=>true,'desc'=>'登录密码'),
                'code' => array('name' => 'code','require'=>false,'desc'=>'验证码'),
                'openid' => array('name'=>'openid','require'=>false,'desc'=>'公众号、小程序openId'),
            ),

            'checkUserStatus'=>array()
        );
	}

    /**
     * 通过微信code获取openid
     * @desc 返回用户相关信息<br>Authorization Type: Bear Token<br>"headers" : {'Authorization': 'Bearer '+ token}
     * @return array userInfo 用户信息
     * @return int time 当前时间戳
     */
    public function getOpenId() {
        if($this->appid!=''){
            $wxUser = new WxUser();
            $appInfo = $wxUser->getAppInfo($this->appid);
            $weapp = new WeApp($appInfo['app_id'],$appInfo['app_secret'],'../runtime/cache/');
        }else {
            $weapp = new WeApp(\PhalApi\DI()->config->get('app.wxapp.wx_appid'), \PhalApi\DI()->config->get('app.wxapp.wx_secret'), '../runtime/cache/');
        }
        $code = $this->code;
        $json = $weapp->getSessionKey($code);
        $data = json_decode($json,true);
        if(!empty($data["openid"])){
                return $data;//["openid"];
        }else{
            throw new BadRequestException('获取openid失败!', 1);
        }
    }


    /**
     * 微信登陆
     * @method POST
     * @desc 微信登陆,返回Token
     * @return object UserInfo 用户的详情数据
     * @return string accessToken 获取的accessToken
     * @return int expireTime 具体过期时间，精确到毫秒
     */
    public function accessToken() {
        error_log("login!", 0);
        if($_SERVER['REQUEST_METHOD']=="POST") {
            //$this->username = 'luodong';//$_POST['username'];
            //$this->password = '123456';//$_POST['password'];

            //数据库验证
            $user = new DomainUser();
            $userInfo = $user->getDetail($this->openid,"openid");
            $params = \PhalApi\DI()->request->getAll();
            if(empty($userInfo["id"])){
                $params['create_date'] = time();
                $params['write_date'] = time();
                //生成会员卡号
                $params['user_card'] = date('Ymdhis',$params['create_date']);
                $insertId = $user->add($params);
                //获得注册积分
                $score = new Score();
                $score->addScore($insertId,'2020309','wx_user',$insertId,$this->mall_id);
            }else{
                $user->update($params,$this->openid);
            }
            $userInfo = $user->getDetail($this->openid,"openid");

            if ($userInfo) {
                //获取用户权限信息
                $payload = array(
                    'iss' => $this->key, //签发者
                    'iat' => $_SERVER['REQUEST_TIME'], //什么时候签发的
                    //'exp' => $_SERVER['REQUEST_TIME'] + 43200, //过期时间
                    'nickname' => $userInfo['nickname'],
                    'openid' => $userInfo['openid'],
                    'user_id' => $userInfo['id'],
                    'user_type' => $userInfo['user_type'],
                    'sex' => $userInfo['sex'],
                    'headimgurl' => $userInfo['headimgurl'],
                    'create_date' => $userInfo['create_date'],
                    'user_card'=> $userInfo['user_card']
                );
                $token = \PhalApi\DI()->jwt->encodeJwt($payload);
                $userInfo["accessToken"] = $token;
                $userInfo['user_type_value'] = $this->user_type_option[$userInfo['user_type']];
                return $userInfo;
            }else{
                throw new BadRequestException('用户错误!', 1);
            }
        }else{
            throw new BadRequestException('请求使用POST请求方式', 1);
        }
    }

    /**
     * 刷新token
     * @method POST
     * @desc 微信登陆,返回Token
     * @return object UserInfo 用户的详情数据
     * @return string accessToken 获取的accessToken
     * @return int expireTime 具体过期时间，精确到毫秒
     */
    public function refresToken() {
        error_log("refresToken!", 0);
        if($_SERVER['REQUEST_METHOD']=="POST") {
            $token = $this->checkToken();
            //数据库验证
            $user = new DomainUser();
            $userInfo = $user->getDetail($token['openid'],"openid");

            if ($userInfo) {
                //获取用户权限信息
                $payload = array(
                    'iss' => $this->key , //签发者
                    'iat' => $_SERVER['REQUEST_TIME'], //什么时候签发的
                    //'exp' => $_SERVER['REQUEST_TIME'] + 43200, //过期时间
                    'nickname' => $userInfo['nickname'],
                    'openid' => $userInfo['openid'],
                    'user_id' => $userInfo['id'],
                    'user_type' => $userInfo['user_type'],
                    'sex' => $userInfo['sex'],
                    'headimgurl' => $userInfo['headimgurl'],
                    'create_date' => $userInfo['create_date'],
                    'user_card'=> $userInfo['user_card']
                );
                $token = \PhalApi\DI()->jwt->encodeJwt($payload);
                $userInfo["accessToken"] = $token;
                $userInfo['user_type_value'] = $this->user_type_option[$userInfo['user_type']];
                return $userInfo;
            }else{
                throw new BadRequestException('用户错误!', 1);
            }
        }else{
            throw new BadRequestException('请求使用POST请求方式', 1);
        }
    }

    /**
     * 用户手机登录
     * @method POST
     * @desc 用户手机登录
     * @return object 登录结果
     */
    public function login() {
        error_log("login!", 0);
        if($_SERVER['REQUEST_METHOD']=="POST") {
            //数据库验证
            $user = new SysUser();
            $params = \PhalApi\DI()->request->getAll();
            $userInfo = $user->getUserInfoByMobile($params["mobile"]);

            //如果用户第一次登录,则自动绑定微信帐号
            if(empty($userInfo['openid'])){
                $user->bindOpenId($userInfo['id'],$params['openid']);
            }else{
                //验证绑定微信公众号
                if($userInfo['openid'] != $params['openid']){
                    throw new BadRequestException('您的帐号与绑定微信公众号不一致!', 1);
                }
            }

            if ($userInfo) {
                $password = $params['password'];
                //判断密码是否正确
                $password = md5(trim($password).$this->key);
                $password=$this->encrypt($password);
                if($userInfo['active']==0){
                    throw new BadRequestException('该用户未激活!', 1);
                }elseif($userInfo['active']==2){
                    throw new BadRequestException('该用户已停用!', 1);
                }else {

                    if ($userInfo['password'] != $password ) {
                        throw new BadRequestException('用户名或密码不正确!', 1);
                    } else {
                        //获取用户公司相关信息
                        $company = new Company();
                        $orgstruct_id = $company->getOrgStructParentIdById($userInfo['department_id'],2,'company');//获取该用户的上级公司
                        $companyInfo = $company->getCompany($orgstruct_id);
                        $company_id = $orgstruct_id;
                        $company_type = $companyInfo['company_type'];

                        //获取用户权限信息
                        $payload = array(
                            'iss' => 'fc114', //签发者
                            'iat' => $_SERVER['REQUEST_TIME'], //什么时候签发的
                            //'exp' => $_SERVER['REQUEST_TIME'] + 43200, //过期时间
                            'nickname' => $userInfo['nickname'],

                            'user_name' => $userInfo['user_name'],
                            'true_name' => $userInfo['true_name'],
                            'login_date' => $userInfo['login_date'],
                            'user_type' => $userInfo['user_type'],
                            'user_id' => $userInfo['id'],
                            'openid' => $userInfo['openid'],
                            'role_id' => $userInfo['orgstruct_id'],
                            'department_id' => $userInfo['department_id'],
                            'role_name' => $userInfo['role_name'],
                            'login' => 1, //是否登录,1为已经登录
                            'isadmin' => $userInfo['is_admin'],
                            'city_code' => $userInfo['city_code'],
                            'company_type' => $company_type,
                            'company_id' => $company_id,
                            'city_name' =>'成都'
                        );

                        $token = \PhalApi\DI()->jwt->encodeJwt($payload);
                        $userInfo["accessToken"] = $token;
                        return $userInfo;
                    }
                }
            }else{
                throw new BadRequestException('用户错误!', 1);
            }
        }else{
            throw new BadRequestException('请求使用POST请求方式', 1);
        }
    }

    /**
     * 验证用户状态是否有效[后台用户]
     */
    public function checkUserStatus(){
        $this->user = $this->checkToken();
        $sysUser = new SysUser();
        $rlt = $sysUser->getUserInfo($this->user['user_id'],'id,active');
        return $rlt;
    }

    /**
     * 用户认证
     */
    public function checkToken(){
        //获取用户带来的认证参数token
        $token = Token::checkTokenByParam();
        if(isset($token['ret']) && isset($token['msg'])){
            error_log("Your session has expired, please login again!", 0);
            throw new BadRequestException('您的会话信息已过期，请重新登录!', 3);
        }
        return $token;
    }

    /**
     * 获取客户端传入的token信息
     * @return
     */
    public static function checkTokenByParam(){
        error_log("checkTokenByParam!", 0);
        $JWTstr = '';
        if(isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION'])){
            $JWTstr = $_SERVER['HTTP_AUTHORIZATION'];
        }else{
            throw new BadRequestException('认证信息不存在，请重新登录', 3);
        }
        //本地的时候没有 Bearer 服务器上有Bearer
        $JWTstr = substr($JWTstr,7);
        $token = \PhalApi\DI()->jwt->decodeJwtByParam($JWTstr);
        if(empty($token["user_id"])){
            throw new BadRequestException('用户不存在请重新登陆，请重新登录', 3);
        }
        return $token;
    }

    /* 密码加密 */
    static public function encrypt($password){
        $base = new Base64();
        //$password=$base->enCrypt(strtoupper($password));
        $password=$base->enCrypt($password);
        return $password;
    }

}
